#include"queue.h"

void QInit(Queue* q)
{
	assert(q);

	q->tail = q->head = NULL;
	q->size = 0;
}

void QPush(Queue* q, QDataType data)
{
	assert(q);
	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("malloc");
		return;
	}

	newnode->next = NULL;
	newnode->data = data;

	if (q->head == NULL)
	{
		q->head = q->tail = newnode;
	}
	else
	{
		q->tail->next = newnode;
		q->tail = q->tail->next;
	}
	q->size++;
}

void QPop(Queue* q)
{
	assert(q);
	assert(q->head != NULL);
	if (q->head->next == NULL)
	{
		free(q->head);
		q->head = q->tail = NULL;
	}
	else
	{
		QNode* next = q->head->next;
		free(q->head);
		q->head = next;
	}
	q->size--;
}

QDataType QFront(Queue* q)
{
	assert(q);
	assert(!QEmpty(q));
	return q->head->data;
}

QDataType QBack(Queue* q)
{
	assert(q);
	assert(!QEmpty(q));
	return q->tail->data;
}

int QSize(Queue* q)
{
	assert(q);
	return q->size;
}

bool QEmpty(Queue* q)
{
	assert(q);
	return q->size == 0;
}

void QDestroy(Queue* q)
{
	assert(q);
	QNode* cur = q->head;
	while (cur)
	{
		QNode* next = cur->next;
		free(cur);
		cur = next;
	}
	q->head = NULL;
	q->tail = NULL;
	q->size = 0;
}

/*q->head = (QNode*)malloc(sizeof(QNode));
if (q->head == NULL)
{
	perror("malloc");
	return;
}
q->head = NULL;

q->tail = (QNode*)malloc(sizeof(QNode));
if (q->tail == NULL)
{
	perror("malloc");
	return;
}*/